import { Repository } from 'typeorm';
import { AppDataSource } from '../config/database';
import { User } from '../entities/User';
import { validate } from 'class-validator';
import * as bcrypt from 'bcrypt';

export class UserService {
  private getUserRepository(): Repository<User> {
    if (!AppDataSource.isInitialized) {
      throw new Error('数据库连接未初始化。请确保数据库已正确配置并连接。');
    }
    return AppDataSource.getRepository(User);
  }

  async createUser(userData: Partial<User>): Promise<User> {
    const userRepository = this.getUserRepository();
    const user = userRepository.create(userData);
    
    // 验证数据
    const errors = await validate(user);
    if (errors.length > 0) {
      throw new Error(`验证失败: ${errors.map(e => Object.values(e.constraints || {})).flat().join(', ')}`);
    }

    // 加密密码
    if (user.password) {
      user.password = await bcrypt.hash(user.password, 10);
    }

    return await userRepository.save(user);
  }

  async findUserById(id: number): Promise<User | null> {
    const userRepository = this.getUserRepository();
    return await userRepository.findOne({
      where: { id },
      relations: ['posts'],
    });
  }

  async findUserByEmail(email: string): Promise<User | null> {
    const userRepository = this.getUserRepository();
    return await userRepository.findOne({
      where: { email },
    });
  }

  async findUserByUsername(username: string): Promise<User | null> {
    const userRepository = this.getUserRepository();
    return await userRepository.findOne({
      where: { username },
    });
  }

  async getAllUsers(page: number = 1, limit: number = 10): Promise<{ users: User[]; total: number }> {
    const userRepository = this.getUserRepository();
    const [users, total] = await userRepository.findAndCount({
      skip: (page - 1) * limit,
      take: limit,
      order: { createdAt: 'DESC' },
    });

    return { users, total };
  }

  async updateUser(id: number, updateData: Partial<User>): Promise<User | null> {
    const userRepository = this.getUserRepository();
    const user = await this.findUserById(id);
    if (!user) {
      return null;
    }

    // 如果更新密码，需要加密
    if (updateData.password) {
      updateData.password = await bcrypt.hash(updateData.password, 10);
    }

    Object.assign(user, updateData);
    
    // 验证数据
    const errors = await validate(user);
    if (errors.length > 0) {
      throw new Error(`验证失败: ${errors.map(e => Object.values(e.constraints || {})).flat().join(', ')}`);
    }

    return await userRepository.save(user);
  }

  async deleteUser(id: number): Promise<boolean> {
    const userRepository = this.getUserRepository();
    const result = await userRepository.delete(id);
    return result.affected !== 0;
  }

  async verifyPassword(user: User, password: string): Promise<boolean> {
    if (!user.password) {
      return false;
    }
    return await bcrypt.compare(password, user.password);
  }
}